<template>
  <view class="">
    <u-popup :show="authType !== ''" :round="10" mode="bottom" closeable @close="close" @open="open">
      <view v-if="authType === 'smsLogin'" class="p-20">
        <view class="text-18 font-bold pb-15">绑定手机号</view>
        <view class="text-tips">为了您的账户安全，请使用本人手机号码</view>

        <!-- <u-verification-code>
        </u-verification-code> -->
        <view class="mt-20 pb-10">
          <u-form ref="uFormRef" label-position="left" :label-width="0" :model="form" :rules="rules">
            <u-form-item label="" prop="name" :border-bottom="true">
              <u-input
                v-model="form.name"
                :custom-style="{height: '36px'}"
                placeholder="用户名"
                border="none"
              />
            </u-form-item>
            <u-form-item label="" prop="phone" :border-bottom="true">
              <u-input
                v-model="form.phone"
                :custom-style="{height: '36px'}"
                maxlength="11"
                :focus="phoneFocus"
                placeholder="手机号"
                border="none"
                @blur="phoneFocus=false"
              />
            </u-form-item>
            <u-form-item label="" prop="code" :border-bottom="true" class="mt-10">
              <u-input v-model="form.code" maxlength="4" placeholder="验证码" border="none">
                <template #suffix>
                  <u-code ref="uCodeRef" :seconds="120" @change="codeChange" />
                  <u-button :custom-style="{width: '100px', height: '36px'}" type="info" @click="getCode">
                    <text class="text-12">{{ codeTips }}</text>
                  </u-button>
                </template>
              </u-input>
            </u-form-item>
            <view class="mt-30">
              <u-button size="large" type="primary" :disabled="saveDisabled" @click="save">
                <text class="text-16">绑定</text>
              </u-button>
            </view>
          </u-form>
        </view>

        <view class="" />
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import $ from '@/sheep'
const userStore = $.store('user')
const uFormRef = ref(null)
const uCodeRef = ref(null)
const phoneFocus = ref(false)

// 验证码提示词
const codeTips = ref('')

const patterns = {
  phone: /^1[3456789]\d{9}$/,
  code: /^\d{4,6}$/
}

/**
 * 提交按钮是否禁用
 */
const saveDisabled = computed(() => {
  return !patterns.phone.test(form.phone) || !patterns.code.test(form.code)
})

// 授权弹窗类型
const authType = computed(() => userStore.authType)

// 表单数据
const { form } = $.useForm({
  name: '',
  phone: '',
  code: '',
  login_code: '',
  logo: ''
})

// 表单验证规则
const rules = {
  name: {
    required: true,
    message: '请填写用户名',
    trigger: ['blur', 'change']
  },
  phone: {
    type: 'number',
    required: true,
    message: '请填写手机号',
    pattern: patterns.phone,
    trigger: ['blur', 'change']
  },
  code: {
    type: 'number',
    message: '请填写验证码',
    pattern: patterns.code,
    trigger: ['blur', 'change']
  }
}

function save() {
  uFormRef.value.validate().then(() => {
    $.post('/User/register', form).then(res => {
      if (res.success) {
        userStore.setAuthType('')
        const { path, options } = $.router.getCurrentRoute()
        $.router.redirect(path, options)
      }
      $.utils.toast(res.msg)
    })
  }).catch(err => {
    console.log(err)
  })
}

/**
 * 弹窗打开
 */
function open() {
  // phoneFocus.value = true
}

/**
 * 弹窗关闭
 */
function close() {
  userStore.setAuthType('')
}

/**
 * 验证码倒计时期间，每秒触发一次
 * @param {Object} value
 */
function codeChange(value) {
  codeTips.value = value
}

/**
 * 请求接口获取验证码
 */
function sendCode() {
  $.get('/User/getCode', { phone: form.phone }).then(res => {
    if (res.success) {
      uCodeRef.value.start()
      if (res.data.code) {
        form.code = res.data.code
      }
    }
    $.utils.toast(res.msg)
  })
}

/**
 * 获取验证码
 */
function getCode() {
  uFormRef.value.validateField('phone', (fields) => {
    if (fields.length) {
      phoneFocus.value = true
    } else if (uCodeRef.value.canGetCode) {
      sendCode()
    }
  })
}
</script>

<style>
</style>
